package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.admin.mapper.LoginMapper;
import com.usian.admin.service.LoginService;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;


@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, AdUser> implements LoginService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        //参数校验
        if (dto==null || StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户或密码不正确");
        }

        //根据用户名去数据库查用户
        QueryWrapper<AdUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AdUser::getName,dto.getName());
        List<AdUser> adUserList = this.list(queryWrapper);

        if (adUserList.size()>0){   //判断集合是否有值
            AdUser adUser = adUserList.get(0);   //把下标为0(第一个值)的值取出来
            //用户输入密码+数据库查出来的盐值，生成一个新的md5  密码串  为newPwe
            String newPwe = DigestUtils.md5DigestAsHex((dto.getPassword().concat(adUser.getSalt()).getBytes()));
            //数据库的密码串 比较新生成的密码串
            if (adUser.getPassword().equals(newPwe)){
                HashMap<String, Object> map = new HashMap<>();
                adUser.setPassword("");
                adUser.setSalt("");
                map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
                map.put("user",adUser);
                return ResponseResult.okResult(map);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
    }
}
